package com.ywx.intelligentaicodegeneration.aop;

import com.ywx.intelligentaicodegeneration.annotation.AuthCheck;
import com.ywx.intelligentaicodegeneration.constant.UserConstant;
import com.ywx.intelligentaicodegeneration.exception.BusinessException;
import com.ywx.intelligentaicodegeneration.exception.ErrorCode;
import com.ywx.intelligentaicodegeneration.mode.entity.User;
import com.ywx.intelligentaicodegeneration.mode.enums.UserRoleEnum;
import com.ywx.intelligentaicodegeneration.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
public class AuthInterceptor {

    @Resource
    private UserService userService;

    //定义切面

    /**
     * 执行权限检查
     *
     * @param joinPoint 切点
     * @param authCheck 权限注解
     * @return 拦截器
     * @throws Throwable 抛出异常
     */
    @Around("@annotation(authCheck)")//切点表达式，匹配所有使用了AuthCheck注解的方法
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {

        String mustRole = authCheck.mustRole();
        UserRoleEnum mustRoleEnum = UserRoleEnum.getEnumByValue(mustRole);

        if (mustRoleEnum == null) {
            return joinPoint.proceed();
        }

        //获取到当前请求
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        //获取当前登录用户
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        //权限校验
        UserRoleEnum userRoleEnum = UserRoleEnum.getEnumByValue(currentUser.getUserRole());
        if (userRoleEnum == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        //要有管理员权限
        if (mustRoleEnum == (UserRoleEnum.ADMIN) && userRoleEnum != UserRoleEnum.ADMIN) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

        //放行
        return joinPoint.proceed();
    }


}
